package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.app.model.ComplaintsReport;
import com.app.service.IComplaintsReportService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 投诉举报 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-04-24
 */
@RestController
@RequestMapping("/complaintsReport")
@Slf4j
public class ComplaintsReportController {
    @Autowired
    private IComplaintsReportService complaintsReportService;

    @ApiOperation(value = "获取投诉举报列表", notes = "获取投诉举报列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", required = false, dataType = "String")
    })
    @GetMapping("/adminComplaintsReportList")
    public Result adminGetNoticeList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                     String keyword) {
        Page<ComplaintsReport> complaintsReportPage = new Page<>(page, limit);
        LambdaQueryWrapper<ComplaintsReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ComplaintsReport::getIsDel, 0);
        // 关键字处理
        if (keyword != null && !keyword.isEmpty()) {
            // 防止 SQL 注入
            String safeKeyword = keyword.replace("%", "\\%").replace("_", "\\_");
            queryWrapper.like(ComplaintsReport::getSketch, safeKeyword);
        }
        return Result.success(complaintsReportService.page(complaintsReportPage, queryWrapper));
    }


    // 新增投诉记录
    @ApiOperation(value = "新增投诉记录", notes = "新增一条投诉记录")
    @PostMapping("/save")
    public Result addComplaint(@RequestBody ComplaintsReport complaintsReport) {
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        // 数据校验
        if (complaintsReport == null || complaintsReport.getSketch() == null || complaintsReport.getSketch().isEmpty()) {
            return Result.error("投诉内容不能为空");
        }

        // 处理图片列表
        if (!complaintsReport.getImageList().isEmpty()) {
            String joinedImages = String.join(",", complaintsReport.getImageList());
            complaintsReport.setImage(joinedImages);
        }
        complaintsReport.setUserId(loginIdAsInt);
        complaintsReport.setIsDel(0); // 默认未删除
        complaintsReport.setIsReply(0); // 默认未回复
        complaintsReport.setCreateTime(LocalDateTime.now());
        try {
            boolean isSaved = complaintsReportService.save(complaintsReport);
            return isSaved ? Result.success("投诉记录添加成功") : Result.error("投诉记录添加失败");
        } catch (Exception e) {
            // 记录日志
            log.error("保存投诉记录时发生异常", e);
            return Result.error("系统异常，投诉记录添加失败");
        }
    }


    // 删除投诉记录
    @ApiOperation(value = "删除投诉记录", notes = "根据id删除一条投诉记录")
    @ApiImplicitParam(name = "id", value = "投诉记录ID", required = true, dataType = "Integer")
    @GetMapping("/delete")
    public Result deleteComplaint(Integer id) {
        LambdaQueryWrapper<ComplaintsReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ComplaintsReport::getId, id);
        queryWrapper.eq(ComplaintsReport::getIsDel, 1);
        boolean update = complaintsReportService.update(queryWrapper);
        return update ? Result.success("投诉记录删除成功") : Result.error("投诉记录删除失败");
    }


    @ApiOperation(value = "投诉详情", notes = "投诉详情")
    @ApiImplicitParam(name = "id", value = "投诉记录ID", required = true, dataType = "Integer")
    @GetMapping("/detail")
    public Result detailComplaint(Integer id) {
        try {
            ComplaintsReport complaint = complaintsReportService.getById(id);
            if (complaint == null) {
                return Result.error("投诉记录不存在");
            }
            if (complaint.getImage() != null && !complaint.getImage().isEmpty()) {
                String[] imageArray = complaint.getImage().split(",");
                complaint.setImageList(Arrays.asList(imageArray));
            }
            return Result.success(complaint);
        } catch (Exception e) {
            return Result.error("获取投诉详情失败，请稍后重试");
        }
    }


    // 根据user_id查询投诉记录
    @ApiOperation(value = "查询我的投诉记录", notes = "根据用户ID查询其所有投诉记录")
    @GetMapping("/userList")
    public Result getComplaintsByUserId(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        Page<ComplaintsReport> complaintsReportPage = new Page<>(page, limit);
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<ComplaintsReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ComplaintsReport::getUserId, loginIdAsInt)
                .eq(ComplaintsReport::getIsDel, 0);
        Page<ComplaintsReport> reportPage = complaintsReportService.page(complaintsReportPage, queryWrapper);

        // 处理image字段转换为imageList
        reportPage.getRecords().forEach(complaint -> {
            if (complaint.getImage() != null && !complaint.getImage().isEmpty()) {
                String[] imageArray = complaint.getImage().split(",");
                complaint.setImageList(Arrays.asList(imageArray));
            }
        });

        return Result.success(reportPage);
    }

    // 回复投诉
    @ApiOperation(value = "回复投诉", notes = "根据id对投诉记录进行回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "投诉记录ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "replyContent", value = "回复内容", required = true, dataType = "String")
    })
    @PostMapping("/reply")
    public Result replyToComplaint(@RequestBody ComplaintsReport complaintsRequest) {
        try {
            ComplaintsReport complaintsReport = complaintsReportService.getById(complaintsRequest.getId());
            if (complaintsReport == null) {
                return Result.error("投诉记录不存在");
            }
            // 封装设置回复状态和内容的方法
            setReplyInfo(complaintsReport, complaintsRequest.getReplyContent());
            boolean isUpdated = complaintsReportService.updateById(complaintsReport);
            return isUpdated ? Result.success("回复成功") : Result.error("回复失败");
        } catch (Exception e) {
            // 记录日志并返回错误信息
            log.error("回复投诉时发生异常", e);
            return Result.error("系统异常，请稍后重试");
        }
    }

    // 封装设置回复状态和内容的方法
    private void setReplyInfo(ComplaintsReport complaintsReport, String replyContent) {
        complaintsReport.setIsReply(1); // 标记为已回复
        complaintsReport.setReplyContent(replyContent); // 设置回复内容
    }

}

